package com.lining.orangeservice.service.impl;

import com.lining.orangeservice.common.BusinessException;
import com.lining.orangeservice.common.enums.ErrorCode;
import com.lining.orangeservice.entity.dto.request.PermissionCreateRequest;
import com.lining.orangeservice.entity.dto.request.PermissionUpdateRequest;
import com.lining.orangeservice.entity.po.Permission;
import com.lining.orangeservice.mapper.PermissionMapper;
import com.lining.orangeservice.service.PermissionService;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public void createPermission(PermissionCreateRequest request) {
        // 验证权限名称是否已存在
        if (permissionMapper.countByName(request.getName()) > 0) {
            throw new BusinessException(ErrorCode.PERMISSION_NAME_EXISTS);
        }

        // 创建权限对象
        Permission permission = new Permission();
        permission.setPermName(request.getName());
        permission.setPermCode(request.getCode());
        permission.setPermType(request.getPermType());
        permission.setParentId(request.getParentId() != null ? request.getParentId() : 0L);
        permission.setPath(request.getPath());
        permission.setComponent(request.getComponent());
        permission.setIcon(request.getIcon());
        permission.setSort(request.getSort());
        permission.setStatus(1); // 默认启用

        // 插入数据库
        permissionMapper.insert(permission);
    }

    @Override
    public void updatePermission(PermissionUpdateRequest request) {
        // 验证权限是否存在
        if (permissionMapper.selectPermissionById(request.getId()) == null) {
            throw new BusinessException(ErrorCode.PERMISSION_NOT_EXISTS);
        }

        // 更新权限信息
        Permission permission = new Permission();
        permission.setId(request.getId());
        permission.setPermName(request.getName());
        permission.setPermCode(request.getCode());
        permission.setPermType(request.getPermType());
        permission.setParentId(request.getParentId() != null ? request.getParentId() : 0L);
        permission.setPath(request.getPath());
        permission.setComponent(request.getComponent());
        permission.setIcon(request.getIcon());
        permission.setSort(request.getSort());

        permissionMapper.update(permission);
    }

    @Override
    public void deletePermission(Long id) {
        // 验证权限是否存在
        if (permissionMapper.selectPermissionById(id) == null) {
            throw new BusinessException(ErrorCode.PERMISSION_NOT_EXISTS);
        }

        // 删除权限
        permissionMapper.delete(id);
    }

    @Override
    public List<Permission> listAllPermissions() {
        return permissionMapper.selectAll();
    }
    
    @Override
    public List<Tree<Long>> getPermissionTree() {
        // 查询所有权限（包括菜单、按钮、接口等所有类型）
        List<Permission> permissions = permissionMapper.selectAllPermissions();
        
        // 转换成TreeNode列表
        List<TreeNode<Long>> nodeList = new ArrayList<>();
        for (Permission permission : permissions) {
            TreeNode<Long> node = new TreeNode<>(
                    permission.getId(),
                    permission.getParentId(),
                    permission.getPermName(),
                    permission.getSort()
            );
            // 添加额外属性
            Map<String, Object> extra = new HashMap<>();
            extra.put("code", permission.getPermCode());
            extra.put("path", permission.getPath());
            extra.put("component", permission.getComponent());
            extra.put("icon", permission.getIcon());
            extra.put("type", permission.getPermType());
            extra.put("status", permission.getStatus());
            node.setExtra(extra);
            nodeList.add(node);
        }
        
        // 构建树形结构
        return TreeUtil.build(nodeList, 0L);
    }

    @Override
    public List<Tree<Long>> getPermissionTreeByUserId(Long userId) {
        // 根据用户ID查询所有权限（包括菜单、按钮、接口等所有类型）
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(userId);
        
        // 转换成TreeNode列表
        List<TreeNode<Long>> nodeList = new ArrayList<>();
        for (Permission permission : permissions) {
            TreeNode<Long> node = new TreeNode<>(
                    permission.getId(),
                    permission.getParentId(),
                    permission.getPermName(),
                    permission.getSort()
            );
            // 添加额外属性
            Map<String, Object> extra = new HashMap<>();
            extra.put("code", permission.getPermCode());
            extra.put("path", permission.getPath());
            extra.put("component", permission.getComponent());
            extra.put("icon", permission.getIcon());
            extra.put("type", permission.getPermType());
            extra.put("status", permission.getStatus());
            node.setExtra(extra);
            nodeList.add(node);
        }
        
        // 构建树形结构
        return TreeUtil.build(nodeList, 0L);
    }

    @Override
    public List<Permission> getAllPermissions() {
        // 查询所有权限（包括菜单、按钮、接口等所有类型）
        return permissionMapper.selectAllPermissions();
    }
    
    @Override
    public List<Permission> getPermissionsByUserId(Long userId) {
        // 根据用户ID查询所有权限（包括菜单、按钮、接口等所有类型）
        return permissionMapper.selectPermissionsByUserId(userId);
    }
}